package com.echo.neocommunity.config;

import com.echo.neocommunity.annotation.LoginRequired;
import com.echo.neocommunity.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            handler=(HandlerMethod) handler;
            LoginRequired methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(LoginRequired.class);
            if(methodAnnotation!=null){
                if(hostHolder.getUser()==null){
                    response.sendRedirect(request.getContextPath()+"/login");
                    return false;
                }
            }else{
                if(hostHolder.getUser()==null){
                    response.sendRedirect(request.getContextPath()+"/login");
                    return false;
                }
            }

        }
        return true;
    }
}
